package com.itheima.controller;

import com.itheima.common.UserExceptionConstant;
import com.itheima.domain.PageBean;
import com.itheima.domain.Result;
import com.itheima.domain.dto.UserEditDTO;
import com.itheima.domain.dto.UserPageDTO;
import com.itheima.domain.po.User;
import com.itheima.exception.UserException;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate template;

    @PostMapping("/register")
    public Result userRegister(@Pattern(regexp = "^\\S{5,10}$") String username,
                               @Pattern(regexp = "^\\S{5,10}$") String password) {

        userService.register(username,password);

        return Result.success();
    }


    @PostMapping("/login")
    public Result useLogin(@Pattern(regexp = "^\\S{5,10}$") String username ,
                           @Pattern(regexp = "^\\S{5,10}$") String password){

        User user = userService.userLogin(username,password);


        if (user == null || user.getStatus() ==0) {
            throw new UserException(UserExceptionConstant.USER_NOT_FIND_);
        }


        HashMap<String, Object> claims = new HashMap<>();

        claims.put("uid",user.getUid());
        claims.put("username",user.getUsername());

        String token = JwtUtil.genToken(claims);

        ValueOperations<String, String> operations = template.opsForValue();

        operations.set("token",token,3, TimeUnit.HOURS);


        return Result.success(token);
    }


    // TODO 文件上传
    @PostMapping("/update")
    public Result userEdit(@RequestBody @Validated UserEditDTO userEditDTO) {

        userService.Edit(userEditDTO);

        return Result.success();
    }


    @GetMapping("/list")
    public Result<PageBean<User>> list(Integer pageNum,Integer pageSize ,
                                       @RequestParam(required = false) String nickname,
                                       @RequestParam(required = false) Integer status) {

        UserPageDTO userPageDTO =new UserPageDTO(pageNum,pageSize,nickname,status);

        PageBean<User> list = userService.list(userPageDTO);

        return Result.success(list);
    }


}
